package com.youlai.boot.common.listener;

import cn.hutool.core.util.ReflectUtil;
import com.mybatisflex.annotation.InsertListener;
import com.youlai.boot.core.security.util.SecurityUtils;
import lombok.extern.log4j.Log4j2;

import java.lang.reflect.Method;

@Log4j2
public class CreatedByListener implements InsertListener {
    @Override
    public void onInsert(Object entity) {
        Method createBy = ReflectUtil.getMethodByName(entity.getClass(), "setCreateBy");
        Method updateBy = ReflectUtil.getMethodByName(entity.getClass(), "setUpdateBy");

        if (SecurityUtils.getUserId() != null) {
            if (createBy != null) {
                ReflectUtil.invoke(entity, "setCreateBy", SecurityUtils.getUserId());
            }

            if (updateBy != null) {
                ReflectUtil.invoke(entity, "setUpdateBy", SecurityUtils.getUserId());
            }
        }
    }
}
